package com.campus.counseling.service.impl;

import com.campus.counseling.entity.ChatAnalysis;
import com.campus.counseling.model.mapper.ChatAnalysisMapper;
import com.campus.counseling.service.ChatAnalysisService;
import com.campus.counseling.service.LSTMAnalysisService;
import com.campus.counseling.model.common.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ChatAnalysisServiceImpl implements ChatAnalysisService {

    private final LSTMAnalysisService lstmAnalysisService;
    private final ChatAnalysisMapper chatAnalysisMapper;

    @Override
    public BigDecimal analyzeSentiment(List<String> chatHistory) {
        try {
            return lstmAnalysisService.analyzeChatContent(chatHistory);
        } catch (Exception e) {
            log.error("聊天内容情感分析失败", e);
            return BigDecimal.ZERO;
        }
    }

    @Override
    public String analyzeRiskLevel(List<String> chatHistory) {
        BigDecimal sentiment = analyzeSentiment(chatHistory);
        return determineRiskLevel(sentiment);
    }

    @Override
    public void saveAnalysisResult(Long userId, Long messageId, BigDecimal score, String riskLevel) {
        log.info("保存情感分析结果: userId={}, messageId={}, score={}, riskLevel={}", 
            userId, messageId, score, riskLevel);
            
        ChatAnalysis analysis = new ChatAnalysis();
        analysis.setUserId(userId);
        analysis.setMessageId(messageId);
        analysis.setSentimentScore(score);
        analysis.setEmotionType(riskLevel);
        analysis.setAnalysisTime(LocalDateTime.now());
        analysis.setCreateTime(LocalDateTime.now());
        
        try {
            chatAnalysisMapper.insert(analysis);
            log.info("情感分析结果保存成功，ID: {}", analysis.getId());
        } catch (Exception e) {
            log.error("保存情感分析结果失败", e);
            throw new ServiceException("保存情感分析结果失败: " + e.getMessage());
        }
    }

    @Override
    public List<ChatAnalysis> findByUserId(Long userId) {
        return chatAnalysisMapper.findByUserId(userId);
    }

    @Override
    public ChatAnalysis getLatestAnalysis(Long userId) {
        return chatAnalysisMapper.findLatestByUserId(userId);
    }

    private String determineRiskLevel(BigDecimal sentiment) {
        if (sentiment.compareTo(new BigDecimal("0.7")) >= 0) {
            return "HIGH_RISK";
        } else if (sentiment.compareTo(new BigDecimal("0.4")) >= 0) {
            return "MEDIUM_RISK";
        } else {
            return "LOW_RISK";
        }
    }
} 